package com.wanggsx.library.util.fun.media.player;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

/**
 * Created by wanggsx on 15/12/10.
 */
public class VoicePlayerManager {
    MediaPlayer mediaPlayer = null;
    VoicePlayerListener oldListener;


    public boolean playVoiceFile(String file, final VoicePlayerListener listener) {
        stopVoicePlaying(oldListener);
        oldListener = listener;
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(file);
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (oldListener != null) {
                        oldListener.onCompletion();
                    }
                }
            });
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean playVoiceUrl(Context ctx, String url, final VoicePlayerListener listener) {
        stopVoicePlaying(listener);
        oldListener = listener;
        if (mediaPlayer==null){
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.setDataSource(ctx,Uri.parse(url));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (oldListener != null) {
                        oldListener.onCompletion();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void stopVoicePlaying(final VoicePlayerListener listener) {
        if (mediaPlayer != null) {
            if (listener != null) {
                listener.onCompletion();
            }
            mediaPlayer.stop();
            mediaPlayer = null;
        }
    }

}
